<template>
  <div class="w-full min-h-screen bg-bg-color">
    <CommonHead />
    <main class="mt-small lg:mt-big">
      <!--      商品顶部展示内容-->
      <SkipHydration>
        <NewDetailBanner />
      </SkipHydration>
      <!-- 除了顶部展示 之外的所有 -->
      <div class="px-3.5 box-border w-full lg:w-100 lg:mx-auto">
        <!-- skuList 和 数量 -->
        <p class="hidden lg:block text-xl text-white lg:mt-8 lg:mb-6">{{ $mt('Select Denomination') }}</p>
        <div class="lg:flex justify-between items-start">
          <DetailNewGoodsListContent class="hidden lg:block flex-1 lg:ltr:mr-5 lg:rtl:ml-5 lg:shrink-0" />
          <DetailCommon class="lg:w-[390px] mt-4 lg:mt-[unset]">
            <NewDetailNum />
          </DetailCommon>
        </div>
        <!-- skuList 和 数量 -->
        <!-- 下面的所有 -->
        <SkipHydration>
          <div class="lg:flex flex-wrap items-start justify-between">
            <!-- Description  -->
            <DetailCommon class="mt-4 ml-0 mr-0 lg:w-[960px]" :title="$mt('Description')">
              <article v-html="withNoFollow(curGoodsDetail.content)" class="text-gray-light goods-article"></article>
            </DetailCommon>
            <!-- 关联商品 -->
            <div class="lg:w-[390px]">
              <DetailCommon class="mt-4" :title="$mt('Related Products')">
                <NewDetailRelate />
              </DetailCommon>
              <DetailCommon class="mt-4" v-if="curGoodsDetail.recommendGame" :title="$mt('Related Information')">
                <section class="grid grid-cols-1 gap-y-3">
                  <IntroduceItem class="w-2/3" :is-show-bg="true" :dataInfo="curGoodsDetail.recommendGame" />
                </section>
              </DetailCommon>
            </div>
            <!-- Description 和 reviews-->
            <div class="lg:flex-1 lg:ltr:mr-5 lg:rtl:ml-5">
              <!-- reviews -->
              <DetailCommon class="mt-4" v-if="!curGoodsDetail.isWalletPurchaseGoods" :title="$mt('Customer Reviews')">
                <template #right>
                  <nuxt-link external :to="$localePath(`/reviews/${curGoodsDetail.urlName}`)" class="flex items-center">
                    <span class="text-sm lg:text-base text-[rgba(255,255,255,0.6)] mr-2">{{ $mt('see all') }}</span>
                    <w-image class="w-3.5 h-3.5" :src="useAsset('detail/item_icon_arrow.png')" />
                  </nuxt-link>
                </template>
                <template #default>
                  <NewDetailReview />
                </template>
              </DetailCommon>
              <!-- 文章 -->
              <DetailCommon v-if="!curGoodsDetail.isWalletPurchaseGoods" class="mt-4" :title="$mt('Events and Offers')">
                <NewDetailArticle />
              </DetailCommon>
              <DetailCommon class="mt-4" v-if="curGoodsDetail.recommendGoods?.length" :title="$mt('Recommend Goods')">
                <div class="grid lg:grid-cols-5 grid-cols-1 gap-2">
                  <nuxt-link
                    :to="$localePath(`/goods/${sItem.urlName || sItem.id}`)"
                    external
                    class="h-16 group flex cursor-pointer items-center text-[#fff]"
                    v-for="sItem in curGoodsDetail.recommendGoods"
                    :key="sItem.id">
                    <y-image
                      lazy
                      class="w-16 rounded-sm h-16 object-contain object-left ltr:mr-2.5 rtl:ml-2.5 shrink-0"
                      :alt="`how to top up ${sItem.name}`"
                      :src="$withPicOrigin(sItem.smallIcon)"
                      height="60"
                      width="60" />
                    <div>
                      <h3
                        class="break-all group-hover:underline line-clamp-2 text-sm lg:text-base lg:font-normal text-white1">
                        {{ sItem.name }}
                      </h3>
                      <span class="mt-0.5 text-xs line-clamp-1 text-gray-light text-[rgba(255,255,255,0.6)]">
                        {{ sItem.areaCode }}
                      </span>
                    </div>
                  </nuxt-link>
                </div>
              </DetailCommon>
              <DetailCommon class="mt-4" :title="$mt('Frequently Asked Questions')">
                <GoodsFAQ />
              </DetailCommon>
            </div>
          </div>
        </SkipHydration>
      </div>
      <!-- 除了banner 之外的所有 -->
      <SkipHydration>
        <NewHomeFoot />
      </SkipHydration>
    </main>
  </div>
</template>

<script setup lang="ts">
import CommonHead from '~/components/basis/CommonHead.vue'
import NewHomeFoot from '~/components/home/NewHomeFoot.vue'
import NewDetailBanner from '~/components/detail/NewDetailBanner.vue'
import NewDetailNum from '~/components/detail/NewDetailNum.vue'
import DetailCommon from '~/components/basis/DetailCommon.vue'
import WImage from '~/components/logic/WImage.vue'
import NewDetailReview from '~/components/detail/NewDetailReview.vue'
import NewDetailRelate from '~/components/detail/NewDetailRelate.vue'
import NewDetailArticle from '~/components/detail/NewDetailArticle.vue'
import { useGoodsStore } from '~/store/goods'
import { useMemberStore } from '~/store/member'
import YImage from '~/components/logic/YImage.vue'
import IntroduceItem from '~/components/introduce/IntroduceItem.vue'
import GoodsFAQ from '~/components/detail/GoodsFAQ.vue'

const isClient = process.client
const { $isPcScreen } = useCommonPlugin()
definePageMeta({ layout: 'plain' })
const skuContainerEl = ref()
const relateGoodsContainerEl = ref()
const { $mt, $localePath } = useCommonPlugin()
const goodsId = ref()
const routeParams = useRoute().params
const goodsStore = useGoodsStore()
const memberStore = useMemberStore()
const withNoFollow = (htmlString) => {
  function addLazyLoading(htmlString) {
    return htmlString.replace(/<img\s(?!.*loading=)/g, '<img loading="lazy" ')
  }

  function addAltToImages(htmlString, altText) {
    // 正则表达式匹配没有alt属性的<img>标签
    const regexWithoutAlt = /<img((?!alt=)[^>])*>/g
    // 为没有alt属性的<img>标签添加alt
    htmlString = htmlString.replace(regexWithoutAlt, (match) => {
      return match.slice(0, -1) + ` alt="${altText}" width='320' height='320'>`
    })

    // 正则表达式匹配已有alt属性的<img>标签
    const regexWithAlt = /<img[^>]*alt=["']([^"']*)["'][^>]*>/g
    // 更新已有alt属性的<img>标签的alt值
    htmlString = htmlString.replace(regexWithAlt, (match, p1) => {
      // 如果alt属性已经有值，则不修改
      // if (p1) {
      //   return match
      // }
      // 如果alt属性为空，则添加指定的altText
      return match.replace(/alt=["']([^"']*)["']/, `alt="${altText}"  width='320' height='320'`)
    })

    return htmlString
  }

  htmlString = htmlString.replace(/<a\b([^>]*)>/gi, function (match, attrs) {
    if (attrs.includes('bittopup.com')) return match
    // 检查是否已经包含 rel 属性
    if (attrs.includes('rel="')) {
      // 如果已有 rel 属性，则追加新值
      return match.replace(/(rel="[^"]*)"/, '$1 nofollow"')
    } else {
      // 如果没有 rel 属性，则添加一个
      return '<a' + attrs + ' rel="nofollow noopener noreferrer">'
    }
  })
  htmlString = htmlString.replace('BITTOPUP', 'BitTopup')
  htmlString = addLazyLoading(htmlString)
  return addAltToImages(htmlString, `How to recharge ${curGoodsDetail.value.name}`)
}
const { data: goodsData } = await useAsyncData(async () => {
  const isGoodsUrlName = isNaN(+routeParams.goodsId)
  if (isGoodsUrlName) return await goodsStore.goodsUrlName2GoodsId(routeParams.goodsId)
  return +routeParams.goodsId
})
// 商品id
goodsId.value = goodsData.value
goodsStore.setGoodsId(unref(goodsId))
// 评论，详情，sku,评论总数据
const { curGoodsReviews, curGoodsDetail, curGoodsSkuInfo, recommendGoodsList, curGoodsSkuList, totalReviewsInfo } =
  storeToRefs(goodsStore)
if (!goodsId.value) throw showError({ statusCode: 404, message: $mt('goods not found') })
await useLazyAsyncData(async () => {
  await Promise.all([
    goodsStore.initGoodsSkuListByGoodsId(),
    goodsStore.fetchReviewsList(1, 6, unref(goodsId)),
    goodsStore.getTotalReviewsInfo(unref(goodsId)),
  ])
  return 1
})
if (!curGoodsDetail.value?.id) throw showError({ statusCode: 500, message: $mt('goods not found') })
if (curGoodsDetail.value?.redirectUrl) {
  navigateTo($localePath(curGoodsDetail.value.redirectUrl), { redirectCode: 301, replace: true })
} else {
  // 重定向的商品就不走下面任务了
  useGoodsSeo({
    curGoodsData: curGoodsDetail.value,
    curGoodsSku: curGoodsSkuInfo.value,
    commentList: curGoodsReviews.value,
    curGoodsSkuList: curGoodsSkuList.value,
  })
  onMounted(() => {
    const cachedSkuId = +localStorage.getItem('cachedSkuId')
    const hasCachedSku = curGoodsSkuList.value.find((item) => item.id === cachedSkuId)
    if (hasCachedSku) goodsStore.setCurSkuId(cachedSkuId)
  })
}
</script>

<style lang="scss">
.goods-article {
  white-space: pre-wrap;
  font-size: 12px;
  @media screen and (min-width: 1024px) {
    font-size: 16px;
  }

  * {
    all: revert;
    word-break: break-word;
  }

  p {
    margin-block-start: 0.7em;
    margin-block-end: 0.7em;
  }

  ol {
    padding-inline-start: 25px;
  }

  ul {
    padding-inline-start: 20px;
  }
}

.goods-article img {
  margin: 0.5em auto 0;
  max-width: 100%;
}

.goods-article a {
  text-decoration: underline;
  color: #0066cc;
  word-break: break-all;
  cursor: pointer;
}
</style>
